package jm.java.bytecode;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @Description 自定义类加载器
 * @date 2022/3/29 16:59
 */
public class LoadClassTest {
    public static void main(String[] args) throws ClassNotFoundException {
        MyClassLoader myClassLoader = new MyClassLoader();
        Class<?> mapImp1 = myClassLoader.loadClass("jm.java.bytecode.AgaCom");
        Class<?> mapImp2 = myClassLoader.loadClass("jm.java.bytecode.AgaCom");
        System.out.println(mapImp2 == mapImp1);


        MyClassLoader myClassLoader2 = new MyClassLoader();
        Class<?> mapImp3 = myClassLoader2.loadClass("jm.java.bytecode.AgaCom");
        System.out.println(mapImp2 == mapImp3);

    }
}

class MyClassLoader extends ClassLoader{

    /**
     *
     * @param name 类名称
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            // 获取本类的字节码文件
            String path = "D:\\NewJava\\JavaFoundation\\java-jvm\\" + name +".class";
            // 文件输出流
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            Files.copy(Paths.get(path),bos);
            // 得到字节数组
            byte[] bytes = bos.toByteArray();

            return defineClass(name,bytes,0, bytes.length);


        } catch (IOException e) {
            e.printStackTrace();
            throw new ClassNotFoundException("类文件未找到：" + e);
        }
    }
}
